package com.example.leetdemo.finash;

public class Solution794 {

    public boolean validTicTacToe(String[] board) {
        int xCount = 0, oCount = 0;
        for (int i = 0 ; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (board[i].charAt(j) == 'X')  xCount += 1;
                if (board[i].charAt(j) == 'O')  oCount += 1;
            }
        }
        if (xCount - oCount < 0 || xCount - oCount > 1) {
            return false;
        }
        int xLine = 0, oLine = 0;
        for (int i = 0; i < 3; i++) {
            if (board[i].charAt(0) == board[i].charAt(1) && board[i].charAt(1) == board[i].charAt(2)) {
                if (board[i].charAt(0) == 'X') xLine++;
                if (board[i].charAt(0) == 'O') oLine++;
            }
            if (board[0].charAt(i) == board[1].charAt(i) && board[1].charAt(i) == board[2].charAt(i)) {
                if (board[0].charAt(i) == 'X') xLine++;
                if (board[0].charAt(i) == 'O') oLine++;
            }
        }
        if (board[0].charAt(0) == board[1].charAt(1) && board[1].charAt(1) == board[2].charAt(2)) {
            if (board[0].charAt(0) == 'X') xLine++;
            if (board[0].charAt(0) == 'O') oLine++;
        }
        if (board[0].charAt(2) == board[1].charAt(1) && board[1].charAt(1) == board[2].charAt(0)) {
            if (board[0].charAt(2) == 'X') xLine++;
            if (board[0].charAt(2) == 'O') oLine++;
        }
        if (xLine == oLine && xLine == 0) {
            return true;
        }
        if (oLine > 0 && xLine == 0 && xCount == oCount) {
            return true;
        }
        if (xLine > 0 && oLine == 0 && xCount > oCount) {
            return true;
        }
        return false;
    }
}
